import os
from django.http import HttpResponse
from rest_framework.views import APIView
from shareAPI2020TB import settings
from BaseWeb import models
def readText(file,encode_info):
    # 2.按行读取
    textlist =[]
    mylen = 0
    for line in open(file, errors='ignore',encoding=encode_info):
        # 清洗空格后如果不为空就下一步处理
        if line.strip() != '':
            # print(f"本行内容为{line}")
            # 每行的数据都需要清洗空格后进行下一步处理
            abc = line.strip()
            mylen = mylen+len(abc)

            if mylen <= 9900:
                textlist.append(abc)
            else:
                break
        else:
            # print("本行为空")
            pass
    print(mylen)
    return textlist
class initData(APIView):
    authentication_classes = []
    def get(self, request, *args, **kwargs):
        try:
            # 获取名字列表
            nameFILE_PATH = os.path.join(settings.MEDIA_ROOT, f'name.txt')  # 获取txt的路径
            nameLIST = readText(nameFILE_PATH, 'UTF-8')
            # 获取图片列表
            imgList = os.listdir(os.path.join(settings.MEDIA_ROOT, f'userHEAD'))  # 只拿到了文件名，没有父路径

            RandomUser = zip(nameLIST, imgList)
            for user in RandomUser:
                RandomUserQuery = models.RandomUserInfo.objects.filter(userName=user[0])
                if not RandomUserQuery:  # 如果查询没有这个名字
                    # 进行保存
                    RandomUserInfoQuerySet = models.RandomUserInfo.objects.create(
                        userName=user[0],
                        user_img=f'userHEAD/{user[1]}'
                    )
                    RandomUserInfoQuerySet.save()
                else:
                    continue
            return HttpResponse("导入成功")
        except Exception as e:
            print(f"初始化随机人名出问题了，请在media目录下加入name.txt和userHEAD文件夹\n {e}")

